package com.aeye.mbr.pt.service.impl;

import com.aeye.mbr.common.base.constants.ErrorCodeConstants;
import com.aeye.mbr.common.exception.ServiceException;
import com.aeye.mbr.ws.api.BaseResp;
import com.aeye.mbr.ws.api.InputData;
import com.aeye.mbr.ws.service.RestfullService;
import org.springframework.beans.factory.InitializingBean;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by shengpeng on 2018/2/9.
 */
public class RestfullServiceImpl implements RestfullService, InitializingBean {

    private Map<String, Method> methodMap = new HashMap<>();

    @Override
    public void afterPropertiesSet() throws Exception {
        for (Method m : this.getClass().getMethods()) {
            if (m.getReturnType().getName().contains("BaseResp")) {
                methodMap.put(m.getName(), m);
            }
        }
    }

    @Override
    public BaseResp invoke(InputData req) throws ServiceException {
        Method m = methodMap.get(req.getFnId());
        if (null == m) {
            return BaseResp.error(ErrorCodeConstants.FNID_NOT_FOUND);
        } else {
            try {
                return (BaseResp) m.invoke(this, req);
            } catch (Exception e) {
                e.printStackTrace();
                return BaseResp.error(ErrorCodeConstants.FAILD);
            }
        }
    }

    public BaseResp helloWorld(InputData req) throws ServiceException {
        return BaseResp.success("Hello World!");
    }

    //TODO more here
}
